package com.nefu.softlab.xjwc.controller;

import com.nefu.softlab.xjwc.model.User;
import com.nefu.softlab.xjwc.shiro.CustomRealm;
import com.nefu.softlab.xjwc.utils.JSONResult;
import com.nefu.softlab.xjwc.utils.LoggerUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author : Ar1es
 * @date : 2020/1/12
 * @since : Java 8
 */
@RestController
@Slf4j
@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
public class LoginController {


    private final CustomRealm customRealm;
    private final LoggerUtil logger;

    @Autowired
    public LoginController(CustomRealm customRealm, LoggerUtil logger) {
        this.customRealm = customRealm;
        this.logger = logger;
    }


    /**
     * 登陆
     * @param phone
     * @param password
     * @param session
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public JSONResult login(@RequestParam("phone") String phone,
                            @RequestParam("password") String password,
                            HttpSession session){
        UsernamePasswordToken token = new UsernamePasswordToken(phone, password);

        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(token);
            logger.info("用户 ：phone: " + phone + " " + "password: " + password + "已登录");
            User user = (User) subject.getPrincipal();
            user.setPassword("");
            session.setAttribute("user", user);
            return JSONResult.ok(user);
        } catch (UnknownAccountException e) {
            return JSONResult.errorMessage(e.getMessage());
        } catch (AuthenticationException e){
            return JSONResult.errorMessage("输入的用户名或密码错误");
        }
    }


    /**
     * 退出
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public JSONResult logout(HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        log.info("用户名 : " + user.getUserName() + "   logout");
        if (subject != null) {
            session.invalidate();
            subject.logout();
            Cache<Object, AuthenticationInfo> authenticationInfoCache = customRealm.getAuthenticationCache();
            if (authenticationInfoCache != null) {
                authenticationInfoCache.remove(user.getPhone());
            }
        }
        return JSONResult.ok();
    }


    /**
     * 未登录提示信息
     * @return
     */
    @RequestMapping(value = "/unAuthor", method = RequestMethod.GET)
    public JSONResult unAuthor(){

        return JSONResult.errorMessage("登录超时或未登录,请重新登录");
    }

    /**
     * 权限不足提示信息
     * @return
     */
    @RequestMapping(value = "/unAuthen", method = RequestMethod.GET)
    public JSONResult unAuthen(){

        return JSONResult.errorRolesMessage("权限不足");
    }

}
